/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BootPageAdapter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.main.adapter;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.LinkedList;
import java.util.List;


public class BootPageAdapter extends PagerAdapter {
    private List<View> views;
    private final LinkedList<View> recyleBin = new LinkedList<>();
    private int[] images;

    public BootPageAdapter(List<View> views, int[] imageIds) {
        this.views = views;
        this.images = imageIds;
    }

    @Override
    public int getCount() {
        return views.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(views.get(position));
    }

    @Override
    public int getItemPosition(Object object) {
        return super.getItemPosition(object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        //在此设置背景图片，提高加载速度，解决OOM问题
        View view;
        int count = getCount();
        if (!recyleBin.isEmpty()) {
            view = recyleBin.pop();
        } else {
            view = views.get(position);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            view.setBackgroundResource(images[position > images.length - 1 ? images.length - 1 : position]);
            view.setLayoutParams(params);
        }
        container.addView(view, 0);
        return views.get(position);
    }
}
